import { CheckBoxSvg, CheckedBoxSvg, DownArrowSvg, LoadingSvg } from "@/app/assets/CustomizeSvg";
import { isLoggedIn } from "@/service/axiosManager";
import { useMainContentContext } from "@/service/general/publicStatic";
import { ToolDetail, ToolExecInfo } from "@/service/request/modal/dataModal";
import { RequestExecTool } from "@/service/request/modal/requestModal";
import { ResponseSingleModal } from "@/service/request/modal/responseModal";
import { execTool, getToolDetail, resetToolPrompt, saveToolPrompt } from "@/service/request/requestApi";
import breaks from "@bytemd/plugin-breaks";
import gfm from "@bytemd/plugin-gfm";
import highlight from "@bytemd/plugin-highlight";
import { Viewer } from "@bytemd/react";
import { message } from "antd";
import { useEffect, useRef, useState } from "react";

import "./utilboxdetail.css"

const UtilBoxDetail = ({data}: {data: ToolDetail}) => {
    const [toolName, setToolName] = useState<string>();
    const [prompt, setPrompt] = useState<string>();
    const [input, setInput] = useState<string>();
    const [output, setOutput] = useState<string>();

    const promptControl = useRef<HTMLTextAreaElement>(null);
    const inputControl = useRef<HTMLTextAreaElement>(null);

    const [loadData, setLoadData] = useState<boolean>(true);
    const [inputAutoWrap, setInputAutoWrap] = useState<boolean>(false);
    const [outputAutoWrap, setOutputAutoWrap] = useState<boolean>(true);
    const [executing, setExecuting] = useState<boolean>(false);

    const {goBack} = useMainContentContext();

    useEffect(() => {
        Initialize();
    });

    const Initialize = () => {
        if (isLoggedIn() && loadData) {
            if (!data?.id) {
                message.error("工具信息异常");
                goBack();
            }
            setLoadData(false);
            initBaseInfo();
            getDetail();
            
        }
    }

    const initBaseInfo = () => {
        setToolName(data.name || "未知工具");
        setPrompt(data.prompt || "");
    }

    const getDetail = () => {
        getToolDetail({id: data.id}).then((res:ResponseSingleModal<ToolExecInfo>) => {
            console.log("工具详情: \n", res);
            if (res.code === 0 && res.success || res.result) {
                setPrompt(res.result?.prompt || "");
                setInput(res.result?.input || "");
                setOutput(res.result?.output || "");
            } else {
                message.error(res.message || "获取工具详情失败");
            }
        }).catch((err) => {
            console.log("获取工具详情失败：\n", err);
        });
    }

    const savePrompt = () => {
        if (!prompt) {
            message.warning("提示词为空");
            promptControl.current?.focus();
            return;
        }
        saveToolPrompt({id: data.id, prompt: prompt}).then((res:ResponseSingleModal<string>) => {
            if (res.code === 200 && res.success && res.result) {
                getDetail();
            } else {
                message.error(res.message || "保存提示词失败");
            }
        }).catch((err) => {
            console.log("保存提示词失败\n", err);
        });
    }

    const resetPrompt = () => {
        resetToolPrompt({id: data.id}).then((res:ResponseSingleModal<string>) => {
            if (res.code === 200 && res.success && res.result) {
                getDetail();
            } else {
                message.error(res.message || "重置提示词失败");
            }
        }).catch((err) => {
            console.log("重置提示词失败\n", err);
        });
    }

    const exec = () => {
        if (executing) return;
        if (!prompt) {
            message.warning("提示词为空");
            promptControl.current?.focus();
            return;
        }
        if (!input) {
            message.warning("输入文本为空");
            inputControl.current?.focus();
            return;
        }
        const param: RequestExecTool = {
            appId: data.id,
            prompt: prompt,
            input: input
        }
        setExecuting(true);
        execTool({param}).then((res:ResponseSingleModal<ToolExecInfo>) => {
            if (res.code === 200 && res.success && res.result) {
                setOutput(res.result.output || "");
            } else {
                message.error(res.message || "重置提示词失败");
            }
            setExecuting(false);
        }).catch((err) => {
            console.log("执行工具失败");
            setExecuting(false);
        });
    }

    return (<>
        <div className="w-full h-full text-black">
            <div className="scrollbar-style w-full h-full flex flex-col items-center justify-start gap-6 py-3 rounded-xl border border-gray-100 shadow-[0_0_5px] shadow-gray-300 bg-white overflow-y-auto">
                <div className="w-full flex flex-row items-center justify-start gap-1 px-5 pb-3 pt-2 border-b border-b-gray-300 cursor-pointer select-none">
                    <div className="rounded-lg px-3 py-1 hover:bg-gray-200 hover:text-blue-600" onClick={() => {goBack()}}>工具箱详情</div>
                    <div className="flex flex-row items-center justify-center w-5 -rotate-90"><DownArrowSvg width={`100%`} height={`100%`} /></div>
                    <div className="px-3 py-1">{toolName}</div>
                </div>
                <div className="w-full flex flex-col items-center justify-center gap-1">
                    <div className="min-w-96 w-4/5 flex flex-row items-center justify-start">
                        <div className="font-bold">提示词</div>
                    </div>
                    <div className="min-w-96 w-4/5 h-40 flex flex-row items-center justify-center gap-3">
                        <div 
                        className="flex-1 h-full flex flex-row items-center justify-center border border-gray-400 rounded-lg p-2 shadow-[0_0_5px] shadow-transparent hover:border-blue-500/60 has-[textarea:focus-within]:border-blue-500/60 has-[textarea:focus-within]:shadow-blue-500"
                        >
                            <textarea 
                            ref={promptControl}
                            name="prompt"
                            value={prompt}
                            placeholder="请输入提示词"
                            className="scrollbar-style w-full h-full outline-none border-none resize-none overflow-y-auto"
                            onChange={(e) => {
                                const value = e.currentTarget.value || e.target.value;
                                setPrompt(item => {return value});
                            }}
                            />
                        </div>
                        <div className="h-full flex flex-col items-center justify-between">
                            <div className="flex flex-row items-center justify-center border border-gray-200 rounded-lg bg-gray-50 px-5 py-1 cursor-pointer hover:bg-blue-500/90 hover:text-white select-none" onClick={savePrompt}>保存</div>
                            <div className="flex flex-row items-center justify-center border border-gray-200 rounded-lg bg-gray-50 px-5 py-1 cursor-pointer hover:bg-blue-500/90 hover:text-white select-none" onClick={resetPrompt}>重置</div>
                        </div>
                    </div>
                </div>
                <div className="w-full flex flex-col items-center justify-center">
                    <div className="w-full flex flex-row items-center justify-center gap-10">
                        <div className="min-w-40 w-2/5 flex flex-col items-center justify-center gap-1">
                            <div className="w-full flex flex-row items-center justify-start">
                                <div className="font-bold">输入</div>
                            </div>
                            <div className="w-full h-full">
                                <div className="h-[520px] flex flex-row items-center justify-center p-2 border border-gray-400 rounded-lg shadow-[0_0_5px] shadow-transparent hover:border-blue-500/60 has-[textarea:focus-within]:border-blue-500/60 has-[textarea:focus-within]:shadow-blue-500">
                                    <textarea
                                    ref={inputControl}
                                    value={input}
                                    placeholder="输入文本"
                                    className={`scrollbar-style w-full h-full outline-none border-none resize-none ${inputAutoWrap ? "overflow-y-auto":"overflow-auto whitespace-nowrap"}`}
                                    onChange={(e) => {
                                        const value = e.currentTarget.value || e.target.value;
                                        setInput(item => {return value});
                                    }}
                                    />
                                </div>
                            </div>
                            <div className="w-full flex flex-row items-center justify-between px-2">
                                <div className="flex flex-row items-center justify-center gap-1 cursor-pointer select-none" onClick={() => {setInputAutoWrap(!inputAutoWrap)}}>
                                    <div className="w-4 flex flex-row items-center justify-center text-blue-600">
                                        {inputAutoWrap ? (<><CheckedBoxSvg width={`100%`} height={`100%`} /></>):(<><CheckBoxSvg width={`100%`} height={`100%`} /></>)}
                                    </div>
                                    <div>自动换行</div>
                                </div>
                                <div>{input?.length || 0}&nbsp;&nbsp;字</div>
                            </div>
                        </div>
                        <div className="min-w-40 w-2/5 flex flex-col items-center justify-center gap-1">
                            <div className="w-full flex flex-row items-center justify-start">
                                <div className="font-bold">输出</div>
                            </div>
                            <div className="relative w-full h-full">
                                <div className="h-[520px] w-full flex flex-row items-start justify-start border p-1 border-gray-400 rounded-lg">
                                    {output ? (<>
                                        <div className={`scrollbar-style w-full h-full p-1 max-lg:max-w-[50vw] max-md:max-w-[40vw] max-w-[60vw] ${outputAutoWrap ? "overflow-y-auto":"overflow-auto"}`}>
                                            <div className={`${outputAutoWrap ? "": "w-max"}`}><Viewer value={output} plugins={[gfm(), breaks(), highlight() ]}/></div>
                                        </div>
                                    </>):(<>
                                        <div className="text-gray-400">输出文本</div>
                                    </>)}
                                </div>
                                <div className={`${executing ? "": "hidden"} absolute top-0 left-0 w-full h-full flex flex-row items-center justify-center rounded-lg bg-black/70 select-none`}>
                                    <div className="w-10 flex flex-row items-center justify-center animate-spin text-white"><LoadingSvg width={`100%`} height={`100%`} /></div>
                                </div>
                            </div>
                            <div className="w-full flex flex-row items-center justify-between px-2">
                                <div className="flex flex-row items-center justify-center gap-1 cursor-pointer select-none" onClick={() => {setOutputAutoWrap(!outputAutoWrap)}}>
                                    <div className="w-4 flex flex-row items-center justify-center text-blue-600">
                                        {outputAutoWrap ? (<><CheckedBoxSvg width={`100%`} height={`100%`} /></>):(<><CheckBoxSvg width={`100%`} height={`100%`} /></>)}
                                    </div>
                                    <div>自动换行</div>
                                </div>
                                <div>{output?.length || 0}&nbsp;&nbsp;字</div>
                            </div>
                        </div>
                    </div>
                    <div className="min-w-96 w-2/5 flex flex-row items-center justify-center py-4">
                        <div className={`flex flex-row items-center justify-center rounded-lg bg-blue-500/80 text-white shadow-[0_0_2px] shadow-transparent px-6 py-2   select-none ${executing ? "cursor-wait": "cursor-pointer hover:bg-blue-500 hover:shadow-blue-600"}`} onClick={exec}>提交</div>
                    </div>
                </div>
            </div>
        </div>
    </>);
}

export {
    UtilBoxDetail
}